import numpy as np
import pylab as pl

class PulseShaping:
    def __init__(self,Fs):
        self.Fs = Fs

    #def rrc(self):


    def rc(self,x,fco,beta):
        ff = np.fft.fftfreq(len(x), 1./self.Fs)
        fco = fco*2
        T = 1./fco
        cut = (1-beta)/(2*T)
        Hf = []
        for i,j in enumerate(ff):
            if abs(j) <= cut:
                Hf += [1]
            elif abs(j) > cut and abs(j) <= (1+beta)/(2*T):
                Hf += [1./2*(1+np.cos(np.pi*T/beta*(abs(j)-cut)))]
            else:
                Hf += [0]
        return np.fft.ifft(np.fft.fft(x)*Hf)



    def rect(self,x,fco):
        ff = np.fft.fftfreq(len(x), 1./self.Fs)

        Hf = []
        for i,j in enumerate(ff):
            if fco >= abs(j):
                Hf += [1]
            else:
                Hf += [0]
        return np.fft.ifft(np.fft.fft(x)*Hf)

class Calc:
    def PAPR(self,x):
        xpow = np.real(x)**2+np.imag(x)**2
        xmean = np.mean(xpow)

        return 10*np.log10(max(xpow)/xmean)
        
    def CCDF(self,x,res):
        xmax = max(x)
        xmin = min(x)
        stepsize=float(xmax-xmin)/float(res)
        
        xhis = np.histogram(x,bins=res,density=True)
        return self.get_cdf(xhis[0],stepsize),xhis[1][1::]

    def get_cdf(self,pdf_array,stepsize):
        ans=[0]
        for i in range(0,len(pdf_array)-1):
            ans.append(ans[i]+(pdf_array[i]+pdf_array[i+1])/2.*stepsize)
        return 1-np.array(ans)

    def EVM(self,x,xmod):
        """ Xmod is the original modulated symbols
        """
        xpow = sum(np.real(xmod)**2+np.imag(xmod)**2)/len(xmod)

        prec = abs(np.array(x)-np.array(xmod))**2

        EVM = np.sqrt(sum(prec)/(len(x)*xpow))*100

        return np.round(EVM,3)

class DataHandling:

    def write_data(self,x,y,fname,xname='x',yname='y'):
        lw = []
        lw += [xname+' '+yname+'\r\n']
        for i0,j0 in enumerate(y):
            if isinstance(x[i0], str)==True:
                lw += [x[i0]+' '+`j0`+'\r\n']
            else:
                lw += [`x[i0]`+' '+`j0`+'\r\n']

        open(fname,'wb').writelines(lw)
